package com.example.fengyungo.utils;

import android.util.Log;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * OkHttp工具类
 *
 * @author XLR
 */
public class OkHttpUtils {

    private static final String TAG = "OkHttpUtils";

    private static final OkHttpClient OK_HTTP_CLIENT = new OkHttpClient();

    /**
     * OkHttp的get请求
     *
     * @param url String
     * @return String响应数据
     * @throws IOException IOException
     */
    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = OK_HTTP_CLIENT.newCall(request);
        Response response;
        response = call.execute();
        // 获取响应数据
        String responseData = response.body().string();
        return responseData;
    }

    /**
     * OkHttp的post请求
     *
     * @param url  String
     * @param json String，要传的json数据
     * @return String responseData
     * @throws IOException IOException
     */
    public static String post(String url, String json) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(json, MediaType.parse("application/json")))
                .build();
        Call call = OK_HTTP_CLIENT.newCall(request);
        Response response;
        response = call.execute();
        // 获取响应数据
        String responseData = response.body().string();
        return responseData;
    }

    /**
     * OkHttp的put请求
     *
     * @param url  String
     * @param json String，要传的json数据
     * @return String响应数据
     * @throws IOException IOException
     */
    public static String put(String url, String json) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .put(RequestBody.create(json, MediaType.parse("application/json")))
                .build();
        Log.d(TAG, "url:" + url + ",json:" + json);
        Call call = OK_HTTP_CLIENT.newCall(request);
        Response response;
        response = call.execute();
        // 获取响应数据
        String responseData = response.body().string();
        return responseData;
    }

    /**
     * 判断是否是一个合法的url
     *
     * @param url String
     * @return boolean
     */
    public static boolean isValidUrl(String url) {
        try {
            new URL(url).toURI();
            return true;
        } catch (MalformedURLException | URISyntaxException e) {
            return false;
        }
    }
}
